package net.fonline.apps;

/**
 * This class implements OnClickEvents for JavaME-touchphones.
 * @author Michael
 */
public class OnClickEvents {

    private EchoCanvas ec;
    private EventEntity root = null;
    private String lastEvent = "";

    public OnClickEvents(EchoCanvas ec) {
        this.ec = ec;
    }

    public void update(int x, int y) {
        x = (int) ((x - this.ec.relX) / this.ec.scale);
        y = (int) ((y - this.ec.relY) / this.ec.scale);
        if (!this.lastEvent.equals("")) {
            return;
        }
        EventEntity e = this.root;
        if (this.root == null) {
            return;
        }
        if (e.collidesWith(x, y)) {
            this.lastEvent = e.getName();
            return;
        }
        do {
            e = e.getNext();
            if (e.collidesWith(x, y)) {
                this.lastEvent = e.getName();
                return;
            }
        } while (e.getNext() != null);
    }

    public boolean check(String name) {
        if (name.equals(this.lastEvent)) {
            this.lastEvent = "";
            return true;
        }
        return false;
    }

    public void append(EventEntity e) {
        if (this.root == null) {
            this.root = e;
            return;
        }
        EventEntity temp = this.root;
        while (temp.getNext() != null) {
            temp = temp.getNext();
        }
        temp.setNext(e);
    }

    public void delete(String name) {
        if (this.root == null) {
            return;
        }
        if (this.root.getName().equals(name)) {
            this.root = this.root.getNext();
        }
        EventEntity e = this.root;
        while ((e.getNext() != null)
                && (!e.getNext().getName().equals(name))) {
            e = e.getNext();
        }
        e.setNext(e.getNext().getNext());
    }
}